import { Injectable, Logger, StreamableFile, UploadedFile } from '@nestjs/common';
import { InjectModel } from '@nestjs/mongoose';
import { Model, StringExpressionOperator } from 'mongoose';
import { OpenApiDocument } from './open-api.schema';
import sharp from 'sharp';
import { WriteStream, createReadStream, createWriteStream, existsSync, mkdirSync } from 'fs';
import ffmpeg from 'fluent-ffmpeg';
import dayjs from 'dayjs';
import { join } from 'path';
import { InjectRepository } from '@nestjs/typeorm';
import { commentsBase, videoBase } from './open-api.entity';
import { Repository } from 'typeorm';
const formattedDate = dayjs().format('YYYY-MM-DD');

@Injectable()
export class OpenApiService {
  private readonly logger = new Logger(OpenApiService.name);

  constructor(
    @InjectRepository(videoBase)
    private videoBase: Repository<videoBase>,
    @InjectRepository(commentsBase)
    private commentsBase: Repository<commentsBase>
  ) { }
  /**
   * 压缩对应图片
  */
  async imgCompress(@UploadedFile() file: Express.Multer.File) {
    // 在此处处理上传后的文件
    // if (file.size <= 2 * 1024 * 1024) {
    //   return file;
    // }
    // 使用 sharp 进行压缩
    const compressedFile = await sharp(file.buffer)
      .resize({ width: 1920, withoutEnlargement: true }) //这里可以写压缩完的尺寸
      .jpeg({ quality: 100 })
      .toBuffer();
    // 写入压缩后的文件到指定的路径
    return {
      compressedFile: compressedFile,
      size: compressedFile.length,
    };
  }
  /**
   * 压缩对应视频
  */
  async videoCompress(videoPath: string, outputPath: string): Promise<void> {
    ffmpeg(videoPath)
      .outputOptions(['-c:v libx264', '-crf 23', '-preset veryfast'])
      .save(outputPath)
      .on('end', () => {
        console.log('压缩成功');
      })
      .on('error', (error) => {
        console.log('上传失败', error);
      });
    // const res =
  }
  /**
   *  压缩对应模型 
  */
  // async modelCompress(Data: ArrayBuffer): Promise<boolean> {
  //   try {

  //     // 返回压缩后的数据
  //     return encodedData;
  //     return true;
  //   } catch (err) {
  //     this.logger.error(this.modelCompress.name, err)
  //     return false;
  //   }
  // }
  /**
   * 把文件写入服务器
  */
  async saveFileToServer(
    filePath: string,
    file: Buffer,
    fileName: string,
  ): Promise<void> {
    try {
      if (!existsSync(filePath)) {
        mkdirSync(filePath, { recursive: true });
      }
      const fileStream = createWriteStream(`${filePath}/${fileName}`);
      fileStream.write(file);
    } catch (err) {
      this.logger.error(this.saveFileToServer.name, err)
    }
  }
  /**
   * 通过地址获得模型的服务器文件
  */
  async getModelFileOfPath(path: string) {
    //path：这个地址是服务器文件的地址，可能不带ip的   如果有ip，需要屏蔽掉ip或者域名 可能要用环境变量
    try {

      const fileStream = createReadStream(path);
      return new StreamableFile(fileStream);
    }
    catch (err) {
      this.logger.error(this.getModelFileOfPath.name, err)
    }
  }
  /**
   *  添加视频
  */
  async createVideo(params): Promise<void> {
    try {
      const a = this.videoBase.create(params);
    } catch (err) {
      this.logger.error(this.createVideo.name, err)
    }
  }
  /**
   * 修改视频
   */
  async updateVideo(video_id, params): Promise<void> {
    try {
      const a = this.videoBase.update(video_id, params);
    } catch (err) {
      this.logger.error(this.updateVideo.name, err)
    }
  }
  /**
   * 使用av号搜索视频
   */
  async findOneVideo(video_id: string): Promise<videoBase> {
    const condition: { [key: string]: any } = {};
    try {
      if (video_id) {
        condition.av_id = new RegExp(video_id.trim());
      }
      const data = await this.videoBase.findOne(condition)
      return data;
    } catch (err) {
      this.logger.error(this.createCommit.name, err)
    }
  }
  /**
   * 删除视频
  */
  async removeVideo(video_id: string): Promise<void> {
    try {
      await this.videoBase.delete(video_id);
    }
    catch (err) {
      this.logger.error(this.removeVideo.name, err)
    }
  }
  /**
 *  添加评论
 */
  async createCommit(params: any) {
    try {
      const a = this.commentsBase.create(params);
      console.log('a', a);
    } catch (err) {
      this.logger.error(this.createCommit.name, err)
    }
  }
  /**
   * 批量分页获得av号下面的评论
   */
  async findAllCommit(params: {
    pageSize?: number;
    av_id?: string;
  }): Promise<void> {
    const { pageSize, av_id } = params;
    const condition: { [key: string]: any } = {};
    try {
      if (params.av_id) {
        condition.av_id = new RegExp(params.av_id.trim());
      }
      const total = await this.commentsBase.count(condition);
      const data = await this.commentsBase.findAndCount({ ...condition, skip: pageSize, take: 1000 })
      console.log('data', data);
      console.log('total', total);

    } catch (err) {
      this.logger.error(this.findAllCommit.name, err);
      return null;
    }
  }

  /**
   * 删除评论
   */
  async deleteCommit(comment_id: string): Promise<void> {
    try {
      await this.commentsBase.delete(comment_id);
    }
    catch (err) {
      this.logger.error(this.deleteCommit.name, err);
      return null;
    }
  }
}
